import { Application } from "../Application";
import { logger } from "../util/logger";
import { miscCfg, ScoketRegMsg, SvrInfo } from "../util/defines";
import { TcpSocket } from "./TcpSocket";

/**
 * 未注册的TcpSocket
 */
export class TcpUnregedSocket {

    app: Application
    socket: TcpSocket;

    private regTimeoutTimer: NodeJS.Timeout;
    private onScoketReg: (socket: TcpSocket, svr?: SvrInfo) => void;

    constructor(app: Application, socket: TcpSocket, onScoketReg: (socket: TcpSocket, svr?: SvrInfo) => void) {
        this.app = app;
        this.socket = socket;
        this.onScoketReg = onScoketReg;
        this.regTimeoutTimer = setTimeout(this.onRegTimeout.bind(this), miscCfg.RegTimeout);
        socket.dataMaxLen = miscCfg.dataMaxLenUnreg;
        socket.on(this.onData.bind(this), this.onClose.bind(this));
    }

    private onData(data: ScoketRegMsg) {
        let socket = this.socket;
        this.socket.off();
        this.socket = null;
        clearTimeout(this.regTimeoutTimer);

        switch (data.token) {
            default:
                logger.error(`${socket.remoteAddress}注册失败:非法的token`, this, this.onData);
                socket.close();
                return;

            case miscCfg.svrToken:
                let svr = this.app.svrCfgIdMap[data.sid];
                if (!svr) {
                    logger.error(`${socket.remoteAddress}没找到${data.sid}的服务器配置`, this, this.onData);
                    socket.close();
                    return;
                }
                this.onScoketReg(socket, svr);
                break;

            case miscCfg.cliToken:
                this.onScoketReg(socket);
                break;
        }
    }

    private onClose() {
        clearTimeout(this.regTimeoutTimer);
    }

    private onRegTimeout() {
        logger.error(`${this.socket.remoteAddress}注册超时`, this, this.onRegTimeout);
        this.socket.close();
    }

}